import random

from . import serializers
from rest_framework.generics import CreateAPIView

import constants
from celery_tasks.sms.tasks import send_sms_code

from django_redis import get_redis_connection
from redis import StrictRedis
from rest_framework.response import Response
from rest_framework.views import APIView

from celery_tasks.sms.yuntongxun.sms import CCP
from users.models import User


class SmsCodeVies(APIView):
	'''
	- url: 	GET  /sms_code/13600000000/
	'''

	def get(self, request, mobile):

		#     判断是否60秒内重复发送：
		strict_redis = get_redis_connection('verify_code')		# type:StrictRedis
		sms_flag = strict_redis.get('sms_flag_{0}'.format(mobile))

		if sms_flag:
			return Response({'message':'请勿频繁发送短信验证码'}, status=400)

		# - 视图核心逻辑:
		#     1. 生成短信验证码
		sms = '%06d' % random.randint(0, 666666)
		print('发送短信验证码: %s %s' % (mobile, sms))

		#2. 发送短信验证码 云通讯
		try:
			# CCP().send_template_sms(mobile, [sms, constants.SMS_CODE_REDIS_EXPIRES // 60], 1)
			send_sms_code.delay(mobile, sms)
		except Exception as e:
			print(e)
			return Response({'message': '第三方短信服务商存在问题'}, status=400)

		#3. 保存短信验证码 Redis
		pipline = strict_redis.pipeline()
		pipline.setex('sms_flag_{0}'.format(mobile), constants.SMS_CODE_REDIS_EXPIRES, True)
		pipline.setex('sms_{0}'.format(mobile), constants.SEND_SMS_CODE_INTERVAL, sms)
		pipline.execute()

		return Response({'message': 'OK'})


# 用户计数API
class UsernameCountView(APIView):
	def get(self, request, username):
		count = User.objects.filter(username=username).count()
		data = {
			'username' : username,
			'count' : count
		}

		return  Response(data)


# 用户注册
class UserView(CreateAPIView):

	serializer_class = serializers.CreateUserSerializer